package org.hyn.gateway.socket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.hyn.gateway.session.Configuration;
import org.hyn.gateway.session.defaults.DefaultGatewaySessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.Callable;

/**
 * @author franyhu
 * @description 网关会话服务
 * @date 2025/2/8
 */
public class GatewaySocketServer implements Callable<Channel> {

    private final Logger logger = LoggerFactory.getLogger(GatewaySocketServer.class);

    private final Configuration configuration;
    private DefaultGatewaySessionFactory gatewaySessionFactory;

    private final EventLoopGroup boss = new NioEventLoopGroup(1);
    private final EventLoopGroup work = new NioEventLoopGroup();
    private Channel channel;

    public GatewaySocketServer(Configuration configuration, DefaultGatewaySessionFactory gatewaySessionFactory) {
        this.configuration = configuration;
        this.gatewaySessionFactory = gatewaySessionFactory;
    }

    @Override
    public Channel call() throws Exception {
        ChannelFuture channelFuture = null;
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(boss, work) //将之前创建的两个 EventLoopGroup 传入，分别用于处理新连接和已连接的客户端。
                    .channel(NioServerSocketChannel.class) //指定使用非阻塞的 NIO 通道来处理网络事件。
                    .option(ChannelOption.SO_BACKLOG, 128) //设置 TCP 连接请求队列的大小，128 表示在服务器未处理的连接请求数。
                    .childHandler(new GatewayChannelInitializer(configuration, gatewaySessionFactory));

            // syncUninterruptibly() 同步等待绑定操作完成，期间不会被中断。
            // 适合在服务器启动时使用，确保绑定成功后再继续执行后续逻辑。
            channelFuture = b.bind(new InetSocketAddress(7397)).syncUninterruptibly();
            // TODO 等待关闭 这行代码会阻塞当前线程，直到服务器通道关闭。这通常发生在服务器被停止时。

            channel = channelFuture.channel();
        } catch (Exception e) {
            logger.error("socket server start error.", e);
        } finally {
            if (channelFuture != null && channelFuture.isSuccess()) {
                logger.info("socket server start success.");
            } else {
                logger.error("socket server start error.");
            }
        }
        return channel;
    }
}
